﻿using System;
using System.Collections;
using System.Collections.Generic;
using Ding.Locking;

namespace Ding.Collections.Concurrent
{
    /// <summary>
    /// This class serves as a thread-safe wrapper for an <c>IEnumerator</c> implementation.
    /// It locks as soon as the instance is created and will release the lock once disposed.
    /// </summary>
    /// <typeparam name="T">The type of the enumerator.</typeparam>
    public class LockingEnumerator<T> : IEnumerator<T>, IEnumerator, IDisposable
    {
        private readonly IEnumerator<T> _enumerator;
        private readonly ILock _lock;

        public LockingEnumerator(IEnumerator<T> enumerator, ILock @lock)
        {
            _enumerator = enumerator;
            _lock = @lock;

            _lock.Lock();
        }

        public void Dispose()
        {
            _lock.Unlock();
        }

        public bool MoveNext()
        {
            return _enumerator.MoveNext();
        }

        public void Reset()
        {
            _enumerator.Reset();
        }

        public T Current
        {
            get
            {
                return _enumerator.Current;
            }
        }

        object IEnumerator.Current
        {
            get
            {
                return Current;
            }
        }
    }
}
